package com.feeyo.prophet.config;

import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedList;
import java.util.List;

@Configuration
public class RiakConfig {

    @Value("${riak.hosts}")
    private String hosts;

    @Value("${riak.max-connections:50}")
    private int maxConnections;

    @Value("${riak.min-connections:10}")
    private int minConnections;

    @Value("${riak.retries:5}")
    private int retries;

    @Bean
    public RiakClient riakClient() {
        String[] addresses = hosts.split(",");
        RiakNode.Builder riakNodeBuilder = new RiakNode.Builder()
                .withMinConnections(minConnections)
                .withMaxConnections(maxConnections);

        List<RiakNode> nodes = new LinkedList<>();
        for (String address : addresses) {
            int j = address.indexOf(":");
            nodes.add(riakNodeBuilder.withRemoteAddress(address.substring(0, j))
                    .withRemotePort(Integer.parseInt(address.substring(j + 1))).build());
        }

        RiakCluster riakCluster = RiakCluster.builder(nodes).build();
        riakCluster.start();
        return new RiakClient(riakCluster);
    }
}
